//
//  LSZComposeTextView.swift
//  醒浪微博
//
//  Created by 雷顺哲 on 16/7/18.
//  Copyright © 2016年 LSZ. All rights reserved.
//

import UIKit
//实时看到xib设置的属性
@IBDesignable
class LSZComposeTextView: UITextView {
    
    // MARK: 懒加载控件
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
//        label.text = "听说下雨天音乐跟辣条更配呦~"
        label.numberOfLines = 0
        label.textColor = UIColor.lightGrayColor()
        return label
    }()
    
//    给xib添加设置属性
//    占位文字
    @IBInspectable var placeHolder: String? {
        didSet{
            placeHolderLabel.text = placeHolder
        }
    }
    
//    重写font
    override var font: UIFont? {
        didSet{
            if font == nil {
                return
            }
            placeHolderLabel.font = font
        }
    }
    
//    重写text
    override var text: String? {
        didSet{
            placeHolderLabel.hidden = hasText()
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
//        如果是xib也需要调用
        super.init(coder: aDecoder)
        setUpUI()
    }
//    添加控件设置约束
    private func setUpUI() {
//        监听UITextView文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
        
        addSubview(placeHolderLabel)
        
//        使用手写布局
        
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 8))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
  
    }
    
//     MARK: 监听文字改变的方法
    @objc private func textChange() {
//        判断有内容就隐藏占位的label
        placeHolderLabel.hidden = self.hasText()
    }
    
//    移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
}
